
from tortoise.models import Model
from tortoise import fields

class Cart(Model):
    """购物车模型(适配Tortoise-ORM，物理删除逻辑)"""
    id = fields.IntField(pk=True, autoincrement=True)  # 主键
    user_id = fields.IntField(description="用户ID(与用户绑定)")
    product_id = fields.IntField(description="商品ID")
    product_name = fields.CharField(max_length=255, description="商品名称")
    specs = fields.CharField(max_length=255, description="商品规格（如：尺寸:大; 口味:甜）")
    toppings = fields.CharField(max_length=255, default="", description="选中的小料")
    quantity = fields.IntField(default=1, description="商品数量")
    price = fields.DecimalField(max_digits=10, decimal_places=2, description="加入时的单价（含小料）")
    add_time = fields.DatetimeField(auto_now_add=True, description="加入时间")  # 自动记录创建时间
    update_time = fields.DatetimeField(auto_now=True, description="更新时间")  # 自动记录更新时间
    image_url = fields.CharField(max_length=255, description="图片链接")

    class Meta:
        table = "cart"  # 数据库表名
        indexes = [
            ("user_id",),  # 优化用户维度的列表查询
            ("user_id", "product_id", "specs", "toppings"),  # 优化重复添加判断的查询效率
        ]
        # 联合唯一约束：确保同一用户不会添加完全相同的商品（规格+小料一致）
        unique_together = (("user_id", "product_id", "specs", "toppings"),)

    def __str__(self):
        return f"Cart Item {self.id}: User {self.user_id} - Product {self.product_id}"